<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" title="添加权限">
    <el-tree
      show-checkbox
      :data="menuList"
      :props="defaultProps"
      node-key="id"
      default-expand-all
      :default-checked-keys="menuIds"
      @check="checkTree"
    />
    <template #footer>
      <el-button @click="drawerVisible = false"> 取消 </el-button>
      <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="RightsDrawer">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { Role } from "@/api/system/role";
import { loadSimpleList } from "@/api/system/menu";
import { roleMenuList } from "@/api/system/roleMenu";
const defaultProps = {
  label: "rights"
};
interface DrawerProps {
  row: Partial<Role.ReqRole>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);

const menuList = ref<Menu.MenuOptions[]>([]);
const drawerProps = ref<DrawerProps>({
  row: {}
});
const menuIds = ref<number[]>([]);

const checkTree = (a, b) => {
  menuIds.value = b.checkedKeys;
};

// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  const res = await loadSimpleList();
  if (params.row?.id) {
    const roleRes = await roleMenuList(params.row.id);
    menuIds.value = roleRes.data.map(roleMenu => roleMenu.menuId);
  }
  menuList.value = res.data;
  drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const handleSubmit = async () => {
  try {
    let roleId = drawerProps.value.row.id;
    let params = {
      roleId,
      menuIds: menuIds.value
    };
    await drawerProps.value.api!(params);
    ElMessage.success({ message: `操作成功！` });
    drawerProps.value.getTableList!();
    drawerVisible.value = false;
  } catch (error) {
    console.log(error);
  }
};

defineExpose({
  acceptParams
});
</script>
